﻿Imports System.IO
Imports MeoTom.Core.BLL
Imports MeoTom.Core

Partial Public Class ArticleCreate
    Inherits UI.Page

    Public ObjArticle As New Articles()
    Public ObjTag As New Tags()
    Public Util2 As New Utilities.Common()
    Public StrCatTemp As String = ""

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Response.Buffer = True
        Response.BufferOutput = True

        Dim objCategory As New Categories()
        Dim previousPage As String
        If Request.QueryString.ToString = vbNullString Then
            previousPage = Server.UrlEncode(Request.ServerVariables("PATH_INFO"))
        Else
            previousPage = Server.UrlEncode(Request.ServerVariables("PATH_INFO") & "?" & Request.QueryString.ToString())
        End If
        Util2.ValidateLogin(previousPage)

        GetTag()
        catdetail.InnerHtml = objCategory.WriteCategoryInside(3)
        ArticlePublishContent.InnerHtml = WriteScheduleDate()
        ArticleVisibleContent.InnerHtml = WriteVisibilityInf()
    End Sub

    Public Function WriteScheduleDate() As String
        Dim strOut As New StringBuilder()
        strOut.Append("<br /><select name=""mmmm"" id=""mmmm""><option value=""1"">Jan</option><option value=""2"">Feb</option><option value=""3"">Mar</option><option value=""4"">Apr</option><option value=""5"">May</option><option value=""6"">Jun</option><option value=""7"">Jul</option><option value=""8"">Aug</option><option value=""9"">Sep</option><option value=""10"">Oct</option><option value=""11"">Nov</option><option value=""12"">Dec</option></select> ")
        strOut.Append("<input type=""text"" style=""width:auto;"" id=""dd"" name=""dd"" value=""").Append(Day(DateTime.Now)).Append(""" size=""2"" maxlength=""2"" autocomplete=""off"" />")
        strOut.Append(", <input type=""text"" style=""width:auto;"" id=""yy"" name=""yy"" value=""").Append(Year(DateTime.Now)).Append(""" size=""4"" maxlength=""4"" tabindex=""4"" autocomplete=""off"" /> @ <input style=""width:auto;"" type=""text"" id=""hh"" name=""hh"" value=""").Append(Hour(DateTime.Now)).Append(""" size=""2"" maxlength=""2"" tabindex=""4"" autocomplete=""off"" /> : <input style=""width:auto;"" type=""text"" id=""mn"" name=""mn"" value=""").Append(Minute(DateTime.Now)).Append(""" size=""2"" maxlength=""2"" tabindex=""4"" autocomplete=""off"" /><input type=""hidden"" id=""ss"" name=""ss"" value=""").Append(Second(DateTime.Now)).Append(""" />")
        strOut.Append("<input type=""button"" value=""OK"" class=""button"" onclick=""javascript:Util.PublishConfirmAction();"" /> ")
        strOut.Append("<a onclick=""javascript:Util.CancelArticlePublish();"" title=""Cancel"" href=""#"">Cancel</a><input type=""hidden"" id=""txtReleaseDate"" name=""txtReleaseDate"" />")
        strOut.Append("<script type=""text/javascript"" language=""javascript"">gmobj(""mmmm"").value = ").Append(Month(DateTime.Now)).Append(";</script>")
        Return strOut.ToString()
    End Function

    Public Function WriteVisibilityInf()
        Dim strOut As New StringBuilder()
        strOut.Append("<br /><label><input type=""radio"" name=""cboVisible"" id=""txtArticlePublic"" value=""0"" checked=""checked"" onclick=""javascript:Util.ArticlePublic();"" />Public</label><br />")
        strOut.Append("<label><input type=""radio"" name=""cboVisible"" id=""txtArticlePassword"" value=""1"" onclick=""javascript:Util.ArticlePassword();"" />Password protected</label><br />")
        strOut.Append("<span id=""frmArticlePwd"" style=""font-size:11px;display:none;""><label>Password<br /><input type=""text"" id=""txtArticlePwd"" name=""txtArticlePwd"" /></label><br /></span>")
        strOut.Append("<label><input type=""radio"" name=""cboVisible"" id=""txtArticlePrivate"" value=""2"" onclick=""javascript:Util.ArticlePrivate();"" />Private</label><br />")
        strOut.Append("<input type=""button"" class=""button"" value=""OK"" onclick=""javascript:Util.ConfirmAction('").Append(ArticleVisibleContent.ClientID).Append("');"" />&nbsp;&nbsp;<a href=""#"" title=""Cancel"" onclick=""javascript:Util.CancelArticleVisible('").Append(ArticleVisibleContent.ClientID).Append("');"">Cancel</a>")
        strOut.Append("<input type=""hidden"" name=""txtPostVisible"" id=""txtPostVisible"" value=""0"" />")
        Return strOut.ToString()
    End Function

    Private Sub btnCreate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCreate.Click
        Dim strId As String
        If txtTitle.Text = vbNullString Then
            txtTitle.Text = "No Title"
        ElseIf txtTitle.Text.Length > 550 Then
            txtTitle.Text = Server.HtmlEncode(Left(txtTitle.Text.Trim, 500))
        End If
        ObjArticle.Approved = True
        ArticleInfo()

        If Request.Form("txtTestUrl") = "" Then
            ObjArticle.ArticlePath = "/" & ObjArticle.CreatedDate.Year.ToString() & "/" & ObjArticle.CreatedDate.Month.ToString() & "/" & ObjArticle.CreatedDate.Day.ToString() & "/" & ObjArticle.TitleNone & "-" & Util2.HexValue(ObjArticle.ArticlesId)
        Else
            ObjArticle.ArticlePath = Request.Form("txtTestUrl").Trim & "-" & Util2.HexValue(ObjArticle.ArticlesId)
        End If
        ObjArticle.UpdateArticlePath()

        ObjArticle.WriteXmlbyId(ObjArticle.ArticlesId, ObjArticle.CreatedDate.Day, ObjArticle.CreatedDate.Month, ObjArticle.CreatedDate.Year, ObjArticle.Body, ObjArticle.CategoryId, StrCatTemp)
        ObjArticle.WriteRss(1000000)

        strId = ObjArticle.ArticlesId.ToString()

        ObjArticle.WriteTop10Last()
        ObjArticle.WriteTop10View()
        ObjArticle.WriteTopStory()
        ObjArticle.WriteArchive()

        'Get Default Tag
        ObjTag.GetDefaultTag(0)

        Response.Redirect("/mt-inside/ArticleUpdate.aspx?action=Edit&ID=" & strId & "&MsgID=6")
    End Sub

    Public Sub GetTag()
        tags.InnerHtml = objTag.GetTagByArticleUpdate(txtTag.ClientID)
    End Sub

    Public Sub CreateTag(ByVal tagname As String, ByVal articleId As Integer)
        If Not tagname = vbNullString Then
            For Each Str As String In From str1 In Regex.Split(tagname, ",") Where Not Trim(str1) = ""
                ObjTag.TagName = Str.Trim
                ObjTag.ArticleID = articleId
                ObjTag.Create()
            Next
        End If
    End Sub

    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
        If txtTitle.Text = vbNullString Then
            txtTitle.Text = "No Title"
        ElseIf txtTitle.Text.Length > 550 Then
            txtTitle.Text = Server.HtmlEncode(Left(txtTitle.Text.Trim, 500))
        End If
        ObjArticle.Approved = False
        ArticleInfo()

        If Request.Form("txtTestUrl") = "" Then
            ObjArticle.ArticlePath = "/" & ObjArticle.CreatedDate.Year.ToString() & "/" & ObjArticle.CreatedDate.Month.ToString() & "/" & ObjArticle.CreatedDate.Day.ToString() & "/" & ObjArticle.TitleNone & "-" & Util2.HexValue(ObjArticle.ArticlesId)
        Else
            ObjArticle.ArticlePath = Request.Form("txtTestUrl").Trim & "-" & Util2.HexValue(ObjArticle.ArticlesId)
        End If
        ObjArticle.UpdateArticlePath()

        ObjTag.GetDefaultTag(0)
        ObjArticle.WriteXmlbyId(ObjArticle.ArticlesId, ObjArticle.CreatedDate.Day, ObjArticle.CreatedDate.Month, ObjArticle.CreatedDate.Year, ObjArticle.Body, ObjArticle.CategoryId, StrCatTemp)
        Response.Redirect("/mt-inside/ArticleUpdate.aspx?action=Edit&ID=" & ObjArticle.ArticlesId.ToString() & "&MsgID=7")
    End Sub

    Private Sub ArticleInfo()
        Dim strUserName As String
        objArticle.Title = util2.NoHTML(Server.HtmlEncode(txtTitle.Text.Trim))
        objArticle.Body = txtBody.Value
        objArticle.Abstract = util2.FormatMultiline(util2.NoHTML(txtDesc.Text)) 'Regex.Replace(objArticle.Body, "\t|\r|\n", "")

        'Dim MatchFLVPlayer As Match = Regex.Match(objArticle.Abstract, "<div (?<StringRemove0>.*?)divRemoveMediaPlayer(?<StringRemove2>.*?)>(?<StringRemove1>.*?)</tbody></table></div>")
        'While MatchFLVPlayer.Success
        '    objArticle.Abstract = objArticle.Abstract.Replace(MatchFLVPlayer.Groups("StringRemove1").Value, "")
        '    MatchFLVPlayer = MatchFLVPlayer.NextMatch
        'End While
        'MatchFLVPlayer = Nothing

        'Dim MatchCode As Match = Regex.Match(objArticle.Abstract, "<pre (?<StringRemove0>.*?)code(?<StringRemove2>.*?)>(?<StringRemove1>.*?)</pre>")
        'While MatchCode.Success
        '    objArticle.Abstract = objArticle.Abstract.Replace(MatchCode.Groups("StringRemove1").Value, "")
        '    MatchCode = MatchCode.NextMatch
        'End While
        'MatchCode = Nothing

        'Dim MatchHyperLink As Match = Regex.Match(objArticle.Abstract, "\b([\d\w\.\/\+\-\?\:]*)((ht|f)tp(s|)\:\/\/|[\d\d\d|\d\d]\.[\d\d\d|\d\d]\.|www\.|\.tv|\.ac|\.com|\.edu|\.gov|\.int|\.mil|\.net|\.org|\.biz|\.info|\.name|\.pro|\.museum|\.co)([\d\w\.\/\%\+\-\=\&amp;\?\:\\\&quot;\'\,\|\~\;]*)\b")
        'While MatchHyperLink.Success
        '    objArticle.Abstract = objArticle.Abstract.Replace(MatchHyperLink.Value, "")
        '    MatchHyperLink = MatchHyperLink.NextMatch
        'End While
        'MatchHyperLink = Nothing

        'objArticle.Abstract = Server.HtmlEncode(Left(util2.NoHTML(objArticle.Abstract), 500).Replace(vbCrLf, ""))
        objArticle.IsMedia = drpIsMedia.Checked
        objArticle.IsPicture = drpIsPicture.Checked
        objArticle.IsTopPage = drpIsTopPage.Checked
        objArticle.IsVote = drpIsVote.Checked
        objArticle.CommentEnabled = drpCommentEnabled.Checked
        objArticle.ExpireDate = DateTime.Now.AddYears(1000)
        objArticle.PostVisible = Integer.Parse(Request.Form("txtPostVisible").ToString())
        objArticle.CreatedDate = DateTime.Now
        objArticle.TitleNone = util2.utf8_to_ascii(Server.HtmlDecode(objArticle.Title))

        Try
            If util2.GetCookie("UserID") = vbNullString Then
                objArticle.UserID = Integer.Parse(util2.GetSession("UserID"))
                strUserName = util2.GetSession("UserName")
            Else
                objArticle.UserID = Integer.Parse(util2.GetCookie("UserID"))
                strUserName = util2.GetCookie("UserName")
            End If

            If Request.Form.Get("txtArticlePwd") = vbNullString Then
                objArticle.ArticlePassword = vbNullString
            Else
                objArticle.ArticlePassword = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Request.Form("txtArticlePwd").ToString(), "MD5")
            End If

            Using dc As New MeoTomDataContext
                If Request.Form("txtReleaseDate").ToString() = vbNullString Then
                    objArticle.ReleaseDate = DateTime.Now
                    dc.Justin_PostCount_Update(objArticle.ReleaseDate.Month.ToString & "/" & objArticle.ReleaseDate.Year.ToString, Integer.Parse(Configs.SiteID))
                Else
                    objArticle.ReleaseDate = DateTime.Parse(Request.Form("txtReleaseDate").ToString())
                    dc.Justin_PostCount_Update(objArticle.ReleaseDate.Month.ToString & "/" & objArticle.ReleaseDate.Year.ToString, Integer.Parse(Configs.SiteID))
                End If
            End Using

            If fileUpload.HasFile Then
                Dim randomStr As New Utilities.RandomStrings
                Dim strFileName As String = randomStr.GenerateRandomString(DateTime.Now) & ".jpg"
                Dim strFolder As String = Configs.UserFolder & strUserName & "\" & DateTime.Now.Year.ToString & "\" & Right("0" & DateTime.Now.Month.ToString, 2) & "\" & Right("0" & DateTime.Now.Day.ToString, 2) & "\"
                If Not Directory.Exists(strFolder) Then
                    Directory.CreateDirectory(strFolder)
                End If

                Dim objImage As New Utilities.ImageUtil(fileUpload.PostedFile.InputStream, 1024, 1024, "UploadService", strUserName, strFileName)
                objImage.PublicUpload(228, 0, strFileName, "")

                objArticle.ImagePath = strFolder.Replace(Configs.UserFolder, "").Replace("\", "/") & "228x0__" & strFileName
            Else
                objArticle.ImagePath = ""
            End If

            If Request.Form("txtTestUrl") = "" Then
                objArticle.ArticlePath = "/" & objArticle.CreatedDate.Year.ToString() & "/" & objArticle.CreatedDate.Month.ToString() & "/" & objArticle.CreatedDate.Day.ToString() & "/" & objArticle.TitleNone & "-" & util2.HexValue(objArticle.ArticlesId)
            Else
                objArticle.ArticlePath = Request.Form("txtTestUrl").Trim & "-" & util2.HexValue(objArticle.ArticlesId)
            End If

            'Create Article
            objArticle.Create()

            'Create Article Category
            If Request.Form.Get("cboCategory") = vbNullString Then
                objArticle.CategoryId = 1
                objArticle.SetTempArticleCat(0)
            Else
                For Each strCatId As String In Regex.Split(Request.Form("cboCategory").ToString(), ",")
                    StrCatTemp = strCatId

                    Dim str() As String = StrCatTemp.Split(New Char() {"|"c})
                    ObjArticle.CategoryId = Integer.Parse(str(0))
                    ObjArticle.SetTempArticleCat(0)
                Next
            End If

            'Create New Tag
            CreateTag(txtTag.Text, objArticle.ArticlesId)
        Catch ex As Exception

        End Try
    End Sub
End Class